﻿using UnityEngine;

namespace HKTools
{
    public class HK_DialogAutoRotAndScale : MonoBehaviour
    {
        [Header("是否自动朝向玩家："), SerializeField] bool isLookAtCam;
        [Header("是否自动缩放："), SerializeField] bool isCanAutoScale;

        [Header("默认摄像机距离："), SerializeField] Vector2 camRange;
        [Header("缩放最小值："), SerializeField, Range(0, 1)] float minimum = 1f;
        [Header("缩放最大值："), SerializeField, Range(1, 2)] float maximum = 2f;

        float initScale;
        float defaultCamDis;

        Transform mainCam_TF;

        void Awake()
        {
            mainCam_TF = Camera.main.transform;

            initScale = transform.localScale.x;
            defaultCamDis = (camRange.y + camRange.x) / 2f;
        }

        void Update()
        {
            if (isCanAutoScale)
                SetAutoScale();

            if (isLookAtCam)
            {
                transform.LookAt(new Vector3(mainCam_TF.position.x, transform.position.y, mainCam_TF.position.z), Vector3.up);
                transform.localEulerAngles = transform.localEulerAngles + new Vector3(0, 180, 0);
            }
        }

        float index = 0;
        float camDis;

        void SetAutoScale()
        {
            camDis = Vector3.Distance(transform.position, Camera.main.transform.position);

            if (camDis < defaultCamDis)
            {
                if (camDis - camRange.x >= 0)
                    index = (camDis - camRange.x) / (defaultCamDis - camRange.x) - 1;
                else
                    index = -1;
            }
            else if (camDis > defaultCamDis)
            {
                if (camRange.y - camDis >= 0)
                    index = 1 - (camRange.y - camDis) / (camRange.y - defaultCamDis);
                else
                    index = 1;
            }
            else
            {
                index = 0;
            }

            // 0-1
            index = (index + 1) / 2f * (maximum - minimum) + minimum;
            transform.localScale = initScale * Vector3.one * index;
        }
    }
}